package hk.edu.polyu.comp.motioncapture.analysis.command;

import hk.edu.polyu.comp.motioncapture.Screen;
import hk.edu.polyu.comp.motioncapture.analysis.sequence.PointTrack;
import hk.edu.polyu.comp.motioncapture.collection.*;
import hk.edu.polyu.comp.motioncapture.point.*;

public class Command {

	Screen screen;

	// OptiPlayer
	FrameSet originalFrameSet;

	// OptiFrame
	Frame prevDynamicFrame;

	Frame nextDynamicFrame;

	Frame prevStaticFrame;

	Frame nextStaticFrame;

	private long lastClickTime = 0;

	private boolean bDoubleClick = false;

	private static final int DOUBLE_CLICK_TIME_LIMIT = 1000;

	private Point opt = null;

	public Command(Screen screen) {
		this.screen = screen;
	}

	public void setAnalysisVector(FrameSet frameSet) {

		originalFrameSet = frameSet;

		FrameSet temp1 = new FrameSet(100, 100);
		FrameSet temp2 = new FrameSet(100, 100);

		for (int i = 0; i < frameSet.size() / 2; i++)
			temp1.add(frameSet.frameAt(i));

		for (int i = frameSet.size() / 2; i < frameSet.size(); i++)
			temp2.add(frameSet.frameAt(i));

		PointTrack.analyisiStaticDynamicPoints(temp1, 5);
		prevDynamicFrame = PointTrack.dynamicPointFrame;
		prevStaticFrame = PointTrack.staticPointFrame;

		PointTrack.analyisiStaticDynamicPoints(temp2, 5);
		nextStaticFrame = PointTrack.staticPointFrame;
		nextDynamicFrame = PointTrack.dynamicPointFrame;

	}

	public void setSimpleAnalysisVector(FrameSet frameSet) {

		originalFrameSet = frameSet;

		System.out.println(frameSet.size() + "  " + frameSet.first().size()
				+ "  " + frameSet.last().size());

		prevDynamicFrame = frameSet.first();
		prevStaticFrame = frameSet.first();

		nextStaticFrame = frameSet.last();
		nextDynamicFrame = frameSet.last();
	}

	public Point getReturnPoint() {
		return opt;
	}

	public boolean isMouseMove(int mouseSizeTolerance, int tolerance,
			boolean analysisDynamic) {
		Frame vec1, vec2;

		int tol = tolerance;

		if (analysisDynamic) {
			vec1 = prevDynamicFrame;
			vec2 = nextDynamicFrame;
			tol = tol / 2;
		} else {
			vec1 = prevStaticFrame;
			vec2 = nextStaticFrame;
		}

		if (vec1.size() == 2 && vec2.size() == 2) {
			Point pt1a = vec1.pointAt(0);
			Point pt1b = vec1.pointAt(1);
			Point pt2a = vec2.pointAt(0);
			Point pt2b = vec2.pointAt(1);

			if ((DimensionGeometry.distance(pt1a, pt1b) < mouseSizeTolerance)
					&& (DimensionGeometry.distance(pt2a, pt2b) < mouseSizeTolerance)) {
				Point minPt1 = DimensionGeometry.midPoint(pt1a, pt1b);
				Point minPt2 = DimensionGeometry.midPoint(pt2a, pt2b);

				if (DimensionGeometry.distance(minPt1, minPt2) > tol) {
					opt = minPt2;
					return true;
				} else
					return false;
			}
		}
		if (vec1.size() == 1 && vec2.size() == 1) {
			if (DimensionGeometry.distance(vec1.pointAt(0), vec2.pointAt(0)) > tol) {
				opt = vec2.pointAt(0);
				return true;
			} else
				return false;

		} else
			return false;
	}

	public boolean isDown(int regionSizeTolerance) {
		Frame vec1, vec2;

		vec1 = prevDynamicFrame;
		vec2 = prevStaticFrame;

		if (screen.isExist()) {
			double screenBottom = (screen.getBottomLeftPoint().getY() + screen
					.getBottomRightPoint().getY()) / 2;

			for (Point p : vec1.getPointArray()) {
				if (p.getY() > screenBottom - regionSizeTolerance) {
					return true;
				}
			}

			for (Point p : vec2.getPointArray()) {
				if (p.getY() > screenBottom - regionSizeTolerance) {
					return true;
				}
			}
		}
		return false;
	}

	public boolean isUp(int regionSizeTolerance) {
		Frame vec1, vec2;

		vec1 = prevDynamicFrame;
		vec2 = prevStaticFrame;

		if (screen.isExist()) {
			double screenTop = (screen.getTopLeftPoint().getY() + screen
					.getTopRightPoint().getY()) / 2;

			for (Point p : vec1.getPointArray()) {
				if (p.getY() < screenTop + regionSizeTolerance) {
					return true;
				}
			}

			for (Point p : vec2.getPointArray()) {
				if (p.getY() < screenTop + regionSizeTolerance) {
					return true;
				}
			}
		}
		return false;
	}

	public boolean isCtrlDown() {

		if (screen.isExist())
			if (isPointExist(10, screen.getBottomLeftPoint()))
				return false;
			else
				return true;
		else
			return false;
	}

	public boolean isMouseRightClick(int tolerance) {
		if (screen.isExist())
			if (isPointExist(tolerance, screen.getBottomLeftPoint())
					&& isPointExist(tolerance, screen.getTopRightPoint()))
				return false;
			else
				return true;
		else
			return false;
	}

	public boolean isMouseLeftClick(int tolerance) {
		if (screen.isExist())
			if (isPointExist(tolerance, screen.getTopLeftPoint())
					&& isPointExist(tolerance, screen.getBottomRightPoint()))
				return false;
			else
				return true;
		else
			return false;
	}

	public boolean isScrollUp(int tolerance, boolean analysisDynamic) {
		Frame vec1, vec2;

		int tol = tolerance;

		if (analysisDynamic) {
			vec1 = prevDynamicFrame;
			vec2 = nextDynamicFrame;

			tol = tol / 2;
		} else {
			vec1 = prevStaticFrame;
			vec2 = nextStaticFrame;
		}

		if (vec1.size() == 4 && vec2.size() == 4) {
			double area1 = DimensionGeometry.fourPointArea(vec1);
			double area2 = DimensionGeometry.fourPointArea(vec2);

			if ((area2 - area1) > tol) {
				return true;
			} else
				return false;
		} else
			return false;

	}

	public boolean isScrollDown(int tolerance, boolean analysisDynamic) {
		Frame vec1, vec2;
		int tol = tolerance;

		if (analysisDynamic) {
			vec1 = prevDynamicFrame;
			vec2 = nextDynamicFrame;
			tol = tol / 2;
		} else {
			vec1 = prevStaticFrame;
			vec2 = nextStaticFrame;
		}

		if (vec1.size() == 4 && vec2.size() == 4) {
			double area1 = DimensionGeometry.fourPointArea(vec1);
			double area2 = DimensionGeometry.fourPointArea(vec2);

			if ((area1 - area2) > tol) {
				return true;
			} else
				return false;
		} else
			return false;

	}

	public boolean isPointExist(int tolerance, Point opt) {
		try {
			boolean result = false;

			for (int i = 0; i < nextStaticFrame.size(); i++) {
				Point optCheck = nextStaticFrame.pointAt(i);
				if (PointTrack.isInRegion(tolerance, optCheck, opt)) {
					result = true;
				}
			}

			return result;
		} catch (Exception e) {
			// e.printStackTrace();
			return false;
		}
	}

	/**
	 * @deprecated
	 * @param mouseSizeTolerance
	 * @return
	 */
	public boolean isMouseClick(int mouseSizeTolerance) {

		boolean isSingleClick = false;
		// boolean bClick = false;

		// When 2 dynamic is changed to 1 static point, mouse click
		// When 2 dynamic is changed to 1 dynamic point, mouse click
		// /prevStaticFrame.size() == 2 ||

		if (prevDynamicFrame.size() == 2) {

			Point firstPt = null, lastPt = null;

			firstPt = prevDynamicFrame.firstPoint();
			lastPt = prevDynamicFrame.lastPoint();

			// Identify of the two dynamic points is a hand, ignore disappeared
			// far away point
			double distanceBtnTwoPt = DimensionGeometry.distance(firstPt,
					lastPt);
			if (distanceBtnTwoPt < mouseSizeTolerance) {

				// Check the frame contains one point or not
				if (nextDynamicFrame.size() == 1) {

					int tolerance = (int) (distanceBtnTwoPt / 2);

					if (PointTrack.isInRegion(tolerance, nextDynamicFrame
							.firstPoint(), DimensionGeometry.midPoint(firstPt,
							lastPt))) {
						if (System.currentTimeMillis() - lastClickTime > DOUBLE_CLICK_TIME_LIMIT) {
							lastClickTime = System.currentTimeMillis();
							isSingleClick = true;
						}
					}
				}
			}
		}

		return isSingleClick;
	}

	public boolean isMouseDoubleClick() {
		if (bDoubleClick) {
			bDoubleClick = false;
			return true;
		} else
			return false;
	}

	public double getRotation(int tolerance, boolean analysisDynamic) {
		Frame vec1, vec2;

		int tol = tolerance;

		if (analysisDynamic) {
			vec1 = prevDynamicFrame;
			vec2 = nextDynamicFrame;
			tol = tol / 2;
		} else {
			vec1 = prevStaticFrame;
			vec2 = nextStaticFrame;
		}

		if (vec1.size() == 4 && vec2.size() == 4) {
			// System.out.println("rotation 4x4");
			double angle = 0;

			vec1 = DimensionGeometry.giftWrappingBound(vec1);
			vec2 = DimensionGeometry.giftWrappingBound(vec2);

			if (vec1.size() != 4 || vec2.size() != 4) {
				// System.out.println("vec1: " + vec1.size() + " vec2: " +
				// vec2.size());
				return 0;
			}

			// The rectangle is rotating only when its mid-point is unchanged
			Point midPt1 = DimensionGeometry.intersectionPoint(vec1.pointAt(0),
					vec1.pointAt(1), vec1.pointAt(2), vec1.pointAt(3));
			// System.out.println("Mid-Point: " + midPt1);

			Point midPt2 = DimensionGeometry.intersectionPoint(vec2.pointAt(0),
					vec2.pointAt(1), vec2.pointAt(2), vec2.pointAt(3));
			// System.out.println("Mid-Point: " + midPt2);

			if ((midPt1.getX() - midPt2.getX())
					* (midPt1.getX() - midPt2.getX())
					+ (midPt1.getY() - midPt2.getY())
					* (midPt1.getY() - midPt2.getY()) > tol * tol) {
				// System.out.println("Spanning");
				// return false;

				// // Compute the slope different of the two diagonal lines
				// double pd1 = DimensionGeometry.slope(vec1.pointAt(0), vec1
				// .pointAt(2));
				// double cd1 = DimensionGeometry.slope(vec2.pointAt(0), vec2
				// .pointAt(2));
				//
				// double pd2 = DimensionGeometry.slope(vec1.pointAt(1), vec1
				// .pointAt(3));
				// double cd2 = DimensionGeometry.slope(vec2.pointAt(1), vec2
				// .pointAt(3));
				//
				// // System.out.println(pd1 + " " + cd1 + " " + pd2 + " " +
				// cd2);
				// angle = ((cd1 - pd1) + (cd2 - pd2)) / 2;
				// System.out.println("angle: " + angle);
				// System.out.println("pd1- pd2: " + (pd1 - pd2));

				// Compute the difference in polar angle between two frames of
				// the two diagonal lines
				double angle1 = DimensionGeometry.polarAngle(vec1.pointAt(0),
						vec1.pointAt(2))
						- DimensionGeometry.polarAngle(vec2.pointAt(0), vec2
								.pointAt(2));
				double angle2 = DimensionGeometry.polarAngle(vec1.pointAt(1),
						vec1.pointAt(3))
						- DimensionGeometry.polarAngle(vec2.pointAt(1), vec2
								.pointAt(3));
				// Average the two difference
				angle = (angle1 + angle2) / 2;

				if (Math.abs(angle) > tolerance) {
					return angle;
				}
			}
		}

		return 0;
	}

	/**
	 * Get the facing of the pointing triangle in degree, when the x-axis has
	 * the angle of zero degree
	 * 
	 * @return Polar angle in double, -1 if error
	 */
	public double getFacing() {
		Frame vec = originalFrameSet.last();

		if (vec.size() == 3) {
			int min_id = 0, n;
			double min_len = Double.MAX_VALUE, len;
			Point[] points = vec.getPointArray();

			for (int m = 0; m < 3; m++) {
				n = (m != 2 ? m + 1 : 0);
				len = DimensionGeometry.distance(points[m], points[n]);
				if (len < min_len) {
					min_len = len;
					min_id = m;
				}
			}
			// The closest pair is firstPoint and secondPoint
			Point firstPoint = points[min_id];
			Point secondPoint = points[(min_id != 2 ? min_id + 1 : 0)];
			Point thirdPoint = points[(min_id >= 1 ? min_id - 1 : min_id + 2)];

			Point midPoint = DimensionGeometry
					.midPoint(firstPoint, secondPoint);

			return DimensionGeometry.polarAngle(midPoint, thirdPoint);
		} else
			return -1;
	}
}
